package com.sharkburner.aeris.ui.module.appNavigation.composition;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sharkburner.aeris.bean.MessageResource;
import com.sharkburner.aeris.ui.module.appBody.composition.AppBodyLayout;
import com.sharkburner.aeris.ui.module.appNavigation.model.AppNavigationModel;
import com.sharkburner.aeris.ui.module.appNavigation.model.NavigationFactory;
import com.sharkburner.aeris.ui.module.appNavigation.model.NavigationMenu;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.Item;
import com.vaadin.data.util.HierarchicalContainer;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.ui.Tree;
import com.vaadin.ui.VerticalLayout;

/**
 * @author adarie
 * 
 */
@Component
public class AppNavigationLayout extends VerticalLayout implements
		ItemClickListener {
	private static final String NAME = "ITEM_NAME";
	@AutoGenerated
	private Tree navigation;
	@Autowired
	private AppBodyLayout appBodyLayout;
	@Autowired
	private AppNavigationModel model;
	@Autowired
	private NavigationFactory navigationFactory;

	@Autowired
	private transient MessageResource messageResource;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@PostConstruct
	public void init() {
		setWidth("150px");
		setHeight("100.0%");
		buildMainLayout();
	}

	private void buildMainLayout() {
		navigation = new Tree();
		navigation.setImmediate(false);
		navigation.setWidth("100.0%");
		navigation.setHeight("100.0%");
		navigation.setItemCaptionPropertyId(NAME);

		navigation.setContainerDataSource(buildNavigationTree());

		navigation.addListener(this);
		addComponent(navigation);
	}

	@Override
	public void itemClick(ItemClickEvent event) {
		model.setLayout(this);
		String menuItem = event.getItemId().toString();
		appBodyLayout.setBodyComponent(navigationFactory
				.getBodyLayout(menuItem));
	}

	private HierarchicalContainer buildNavigationTree() {
		HierarchicalContainer container = new HierarchicalContainer();
		container.addContainerProperty(NAME, String.class, "");

		addMenuItem(container, NavigationMenu.MENU_SITE, "menu.site", null);
		addMenuItem(container, NavigationMenu.MENU_RSS, "menu.rss", null);

		return container;
	}

	private void addMenuItem(HierarchicalContainer container, String id,
			String name, Object parentId) {
		Item item = container.addItem(id);
		if (parentId != null) {
			container.setParent(id, parentId);
		}

		item.getItemProperty(NAME).setValue(messageResource.getText(name));
	}
}
